<template>
  <q-page class="cc-admin">
    <div class="col bg-white shadow-2 q-pa-md q-ma-sm">
      <div class="row items-center justify-start q-mb-md">
        <q-item class="col-md-3 col-sm-6 col-xs-12 items-center">
          <q-item-label>许可名称：</q-item-label>
          <q-item-section>
            <q-input dense outlined v-model="searchForm.licenceName"></q-input>
          </q-item-section>
        </q-item>
        <q-item class="col-md-3 col-sm-6 col-xs-12 items-center">
          <q-item-label>所属公司：</q-item-label>
          <q-item-section class="col row">
            <q-select
              dense
              debounce="500"
              hide-bottom-space
              outlined
              :options="sysCompany"
              v-model="searchForm.companyId"
              lazy-rules
              emit-value
              map-options
            />
          </q-item-section>
        </q-item>
        <q-item class="col-md-3 col-sm-6 col-xs-12 items-center">
          <q-item-section>
            <div class="row justify-center">
              <q-btn
                unelevated
                class="q-mr-sm no-border-radius"
                color="primary"
                icon="search"
                label="查询"
                :loading="loading"
                @click="query()"
              />
              <q-btn
                no-wrap
                outline
                unelevated
                class="q-mr-sm no-border-radius"
                color="secondary"
                icon="refresh"
                label="重置"
                @click="searchReset"
              />
            </div>
          </q-item-section>
        </q-item>
      </div>
      <q-table
        flat
        color="primary"
        class="cross_table"
        separator="cell"
        :columns="columns"
        :data="list"
        row-key="id"
        :pagination.sync="pagination"
        :visible-columns="group"
        @request="query"
        :rows-per-page-options="[10, 20, 50, 100]"
        selection="multiple"
        :selected.sync="selected"
      >
        <template v-slot:top="table">
          <div class="row no-wrap full-width">
            <q-space />
            <table-top-btns
              label="许可管理"
              modelName="licence"
              :showAdd="true"
              :showImport="false"
              :showExport="false"
              :table="table"
              :selected="selected"
              :importing="importing"
              :exporting="exporting"
              :importExcelUrlFull="importExcelUrlFull"
              :columns="columns"
              @groupChange="groupChange"
              @add="add"
              @importExcel="importExcel"
              @exportExcel="exportExcel"
              @showConfirm="showConfirm"
            />
          </div>
        </template>
        <template #body-cell-sfsx="props">
          <q-td key="sfsx" :props="props">
            <div>{{ getSfsx(props.row) }}</div>
          </q-td>
        </template>
        <template #body-cell-opt="props">
          <q-td :props="props" :auto-width="true">
            <q-btn
              flat
              round
              dense
              color="primary"
              icon="edit"
              @click="edit(props.row)"
            >
              <q-tooltip>编辑</q-tooltip></q-btn
            >
            <btn-del label="" @confirm="del(props.row)" />
          </q-td>
        </template>
      </q-table>
    </div>
    <q-dialog maximized flat persistent ref="dialog">
      <q-form @submit="submit" class="dialog_card column">
        <h5 class="view_title justify-between q-px-md">
          {{ editType }}
          <q-btn dense outline round icon="clear" size="sm" v-close-popup />
        </h5>
        <q-scroll-area class="col">
          <div class="row q-col-gutter-x-md dialog_form q-pa-md">
            <div class="col-6">
              <h5><q-icon name="star" color="red" /> 许可名称：</h5>
              <q-input
                outlined
                dense
                v-model="form.licenceName"
                type="text"
                :rules="[requiredTest]"
              />
            </div>
            <div class="col-6">
              <h5>说明信息：</h5>
              <q-input outlined dense v-model="form.description" type="text" />
            </div>

            <div class="col-6">
              <h5><q-icon name="star" color="red" />所属公司：</h5>
              <q-select
                outlined
                dense
                emit-value
                v-model="form.companyId"
                map-options
                :options="sysCompany"
                :rules="[requiredTest]"
                @input="companyIdInput(form.companyId, form)"
              />
            </div>
            <div class="col-6">
              <h5>合同编号：</h5>
              <q-input
                outlined
                dense
                v-model="form.contractNumber"
                type="text"
              />
            </div>
            <div class="col-6">
              <h5><q-icon name="star" color="red" /> 许可生效时间：</h5>
              <input-date-picker
                dense
                debounce="500"
                hide-bottom-space
                outlined
                v-model="form.forceDate"
                type="date"
                :form="form"
                lazy-rules
                :rules="[requiredTest]"
              />
            </div>
            <div class="col-6">
              <h5><q-icon name="star" color="red" /> 许可失效时间：</h5>
              <input-date-picker
                dense
                debounce="500"
                hide-bottom-space
                outlined
                v-model="form.deadDate"
                type="date"
                :form="form"
                lazy-rules
                :rules="[requiredTest]"
              />
            </div>
            <div class="col-6">
              <h5>包含产品：</h5>
              <q-input
                v-if="false"
                v-model="form.moduleNames"
                disable
                dense
                hide-bottom-space
                outlined
              />
              <select-search
                dense
                undefined
                debounce="500"
                hide-bottom-space
                outlined
                :options="moduleOptions"
                v-model="form.moduleIds"
                type="select"
                @input="moduleIdsInput(form.moduleIds, form)"
                lazy-rules
                :rules="[]"
                multiple
                clearable
                emit-value
                map-options
              />
            </div>
            <div class="col-6">
              <h5>包含船舶：</h5>
              <q-input
                v-if="false"
                v-model="form.shipNames"
                disable
                dense
                hide-bottom-space
                outlined
              />
              <select-search
                dense
                undefined
                debounce="500"
                hide-bottom-space
                outlined
                :options="shipOptions"
                v-model="form.shipIds"
                type="select"
                @input="shipIdsInput(form.shipIds, form)"
                lazy-rules
                :rules="[]"
                multiple
                clearable
                emit-value
                map-options
              />
            </div>
          </div>
        </q-scroll-area>
        <div class="row justify-center q-pa-md">
          <q-btn
            outline
            color="primary"
            icon="mdi-close-thick"
            label="关闭"
            v-close-popup
          />
          <q-btn
            class="q-mx-md"
            color="primary"
            icon="mdi-check-bold"
            label="提交"
            :loading="loading"
            type="submit"
          />
        </div>
      </q-form>
    </q-dialog>
    <confirm ref="confirmDialog" :msg="confirmMsg" @confirm="deleteBatch()" />
    <q-inner-loading :showing="loading">
      <q-spinner-gears size="50px" color="primary" />
    </q-inner-loading>
  </q-page>
</template>

<script>
import { IndexMixin } from 'boot/mixins';
import { getDictLabel } from 'boot/dictionary';
import confirm from 'components/confirm';
import { requiredTest } from 'boot/inputTest';

export default {
  name: 'SysLicence',
  mixins: [IndexMixin],
  components: {
    confirm,
  },
  data() {
    return {
      sysCompany: [],
      shipOptions: [],
      moduleOptions: [],
      columns: [
        {
          name: 'index',
          align: 'center',
          label: '序号',
          field: 'index',
        },
        {
          name: 'licenceName', align: 'left', label: '许可名称', field: 'licenceName',
        },
        {
          name: 'companyName', align: 'left', label: '所属公司名称', field: 'companyName',
        },
        {
          name: 'forceDate', align: 'left', label: '许可生效时间', field: 'forceDate',
        },
        {
          name: 'deadDate', align: 'left', label: '许可失效时间', field: 'deadDate',
        },
        {
          name: 'sfsx', align: 'left', label: '是否生效', field: 'sfsx',
        },
        {
          name: 'opt', align: 'center', label: '操作', field: 'id',
        },
      ],
      showQuery: true,
      headers: [{ name: 'Authorization', value: localStorage.Authorization }],
      uploadUrl: `${process.env.SERVER_URL}${process.env.BASE_URL}/sys/common/upload`,
      imgUrl: `${process.env.SERVER_URL}${process.env.BASE_URL}/sys/common/static`,
      url: {
        list: '/sys/licence/list',
        add: '/sys/licence/add',
        edit: '/sys/licence/edit',
        copy:
          '/sys/licence/copy',
        delete: '/sys/licence/delete',
        deleteBatch: '/sys/licence/deleteBatch',
        exportXlsUrl: '/sys/licence/exportXls',
        importExcelUrl: '/sys/licence/importExcel',
      },
    };
  },
  methods: {
    requiredTest,
    getDictLabel,
    submit() {
      if (this.form.shipIds instanceof Array) {
        this.form.shipIds = this.form.shipIds.join(',');
      }
      if (this.form.moduleIds instanceof Array) {
        this.form.moduleIds = this.form.moduleIds.join(',');
      }
      let q;
      if (this.editType === '新建') {
        q = this.$axios.post(this.url.add, this.form);
      } else {
        q = this.$axios.put(this.url.edit, this.form);
      }
      return q.then((r) => {
        this.$info(r.message);
        this.$refs.dialog.hide();
      }).finally(() => {
        this.query();
      });
    },
    getNowFormatDate() {
      const date = new Date();
      const seperator1 = '-';
      const year = date.getFullYear();
      let month = date.getMonth() + 1;
      let strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = `0${strDate}`;
      }
      const currentdate = year + seperator1 + month + seperator1 + strDate;
      return currentdate;
    },
    getSfsx(row) {
      let sfsx = '未生效';
      if (new Date(this.getNowFormatDate()).getTime() >= new Date(row.forceDate).getTime()) {
        sfsx = '已生效';
        if (new Date(this.getNowFormatDate()).getTime() >= new Date(row.deadDate).getTime()) {
          sfsx = '已过期';
        }
      }
      return sfsx;
    },
    initDict() {
      this.$axios.get('/sys/company/getCompanyName').then((r) => {
        this.sysCompany = r;
      });
      this.$axios.get('/sys/module/getModule').then((r) => {
        this.moduleOptions = r.result;
      });
    },

    companyIdInput(v, row, editAfter) {
      // 这里给名称字段赋值
      if (v instanceof Array) {
        const nameArray = [];
        this.form.companyName = '';
        v.forEach((id) => {
          const opt = this.sysCompany.find((o) => o.value === id);
          if (opt) {
            nameArray.push(opt.label);
          }
          this.form.companyName = nameArray.join(',');
        });
      } else {
        const opt = this.sysCompany.find((o) => o.value === v);
        this.form.companyName = opt ? opt.label : '';
      }
      if (v) {
        this.$axios.get(`/sys/licence/getShip?companyId=${v}`).then((r) => {
          this.shipOptions = r.result;
        });
      }
    },
    moduleIdsInput(v, row, editAfter) {
      // 这里给名称字段赋值
      if (v instanceof Array) {
        const nameArray = [];
        this.form.moduleNames = '';
        v.forEach((id) => {
          const opt = this.moduleOptions.find((o) => o.value === id);
          if (opt) {
            nameArray.push(opt.label);
          }
          this.form.moduleNames = nameArray.join(',');
        });
      } else {
        const opt = this.moduleOptions.find((o) => o.value === v);
        this.form.moduleNames = opt ? opt.label : '';
      }
    },
    shipIdsInput(v, row, editAfter) {
      // 这里给名称字段赋值
      if (v instanceof Array) {
        const nameArray = [];
        this.form.shipNames = '';
        v.forEach((id) => {
          const opt = this.shipOptions.find((o) => o.value === id);
          if (opt) {
            nameArray.push(opt.label);
          }
          this.form.shipNames = nameArray.join(',');
        });
      } else {
        const opt = this.shipOptions.find((o) => o.value === v);
        this.form.shipNames = opt ? opt.label : '';
      }
    },
    editAfter() {
      if (this.form.shipIds) {
        this.form.shipIds = this.form.shipIds.split(',');
      }
      if (this.form.moduleIds) {
        this.form.moduleIds = this.form.moduleIds.split(',');
      }
      // 只有编辑触发 为 true才进行触发
      if (this.form.companyId) {
        this.companyIdInput(this.form.companyId, {}, true);
      }
      if (this.form.moduleIds) {
        this.moduleIdsInput(this.form.moduleIds, {}, true);
      }
      if (this.form.shipIds) {
        this.shipIdsInput(this.form.shipIds, {}, true);
      }
    },
  },
  mounted() {
    this.initDict();
  },
};
</script>

<style lang="stylus"></style>
